<template>
  <div>
    <van-nav-bar title="登录" fixed placeholder />
    <van-form @submit="onSubmit">
      <van-field v-model="info.mobile" label="手机号" placeholder="请输入手机号" :rules="rules.mobile" />
      <van-field v-model="info.code" label="验证码" placeholder="验证码"
        :rules="rules.code" />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" loading-type="spinner" :loading="isLoading" loading-text="登录中...">提交</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'myLogin',
  components: {

  },
  data () {
    return {
      isLoading: false,
      info: {
        mobile: '',
        code: ''
      },
      rules: {
        mobile: [
          { required: true, message: '请填写手机号' },
          { pattern: /^(?:(?:\+|00)86)?1\d{10}$/, message: '请输入正确的手机号' }
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '请输入6位验证码' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      if (this.info.mobile.trim() === '') return this.$toast('手机号不能为空')
      if (this.info.code.trim() === '') return this.$toast('验证码不能为空')
      try {
        this.isLoading = true
        const res = await loginAPI(this.info)
        console.log(res)
        this.$toast('登陆成功')
        this.$store.commit('user/setToken', res.data)
        // 如果能取到导航守卫query里的back
        if (this.$route.query.back) {
          this.$router.push(this.$route.query.back)
        } else {
          this.$router.push('/layout/home')
        }
      } catch (error) {
        this.$toast('登陆失败')
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>
<style></style>
